//
//  GongHaiKeHuXiangQingViewController.m
//  JuBoCRM
//
//  Created by iMac on 2024/2/19.
//  Copyright © 2024 iningKe. All rights reserved.
//

#import "GongHaiKeHuXiangQingViewController.h"
#import "KeHuXiangQingGenJinJiLuViewController.h"
#import "KeHuXiangXinXiViewController.h"
#import "GongHaiKeHuXiangQingDingBuView.h"
#import "KeHuXiangQingBottomView.h"
#import "KeHuXiangQingCaoZuoRiZhiViewController.h"
#import "GongHaiKeHuXiangQingDiBuView.h"
#import "JMPopupMenuView.h"
#import "GongHaiFenPeiViewController.h"
#import "AlertRemindView.h"
#import "XinJianKeHuViewController.h"
#import "GenJinJiLuViewController.h"
@interface GongHaiKeHuXiangQingViewController (){
    KeHuXiangQingBottomView *manageBottomview;
    GongHaiKeHuXiangQingDiBuView *gongHaiManageView;
    BOOL isMeiQuanXian;
}
//存放排序方式数组
@property (nonatomic, strong) NSMutableArray *dataArr;

@property (nonatomic,strong) NSDictionary *dataDictionary;

@end

@implementation GongHaiKeHuXiangQingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupNavBar];


    // 设置自定义导航栏背景图片
    self.customNavBar.barBackgroundImage = [UIImage imageNamed:@"导航栏"];
    
    
//    [self.customNavBar wr_setRightButtonWithImage:LocalImagePath(@"客户详情关注")];
    
    [self.customNavBar setOnClickRightButton:^{
        
        NSString *url = [NSString stringWithFormat:@"/crmCustomer/star/%@",_customerId];
        [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:url andParas:nil andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
            if(!error){
                if([GetHandleString(_dataDictionary, @"star") integerValue] == 1){
                    [ZZPUtils showWarning:@"已取消关注"];
                    [self.customNavBar wr_setRightButtonWithImage:LocalImagePath(@"客户详情关注")];
                }else{
                    [ZZPUtils showWarning:@"已添加关注"];
                    [self.customNavBar wr_setRightButtonWithImage:LocalImagePath(@"客户详情已关注")];
                }
                NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:_dataDictionary];
                [dataDic setValue:[NSString stringWithFormat:@"%d",![GetHandleString(_dataDictionary, @"star") boolValue]] forKey:@"star"];
                _dataDictionary = dataDic;
            }
        }];
    }];
    

    [self getCoustomerInfoByCoustomerId];
    
    
//    manageBottomview = [KeHuXiangQingBottomView view];
//    [self.view addSubview:manageBottomview];
//    manageBottomview.editLabel.text = @"转移";
//    manageBottomview.editImage.image = LocalImagePath(@"公海客户详情转移");
//    manageBottomview.sd_layout
//    .leftEqualToView(self.view)
//    .bottomEqualToView(self.view)
//    .rightEqualToView(self.view)
//    .heightIs(97);
//    
//    manageBottomview.manageClickBlock = ^(NSInteger index) {
//        if(index == 100){
//            //            写记录
//            GenJinJiLuViewController *xieJiLu = [[GenJinJiLuViewController alloc] init];
//            [self.navigationController pushViewController:xieJiLu animated:YES];
//        }else if(index == 101){
//            //            转移
//            [self zhuanYiGongHai];
//            
//        }else if(index == 102){
//            //            电话
//            if([GetHandleString(_dataDictionary, @"mobile") length] > 0){
//                [ZZPUtils telephoneForAppWithNum:GetHandleString(_dataDictionary, @"mobile")];
//            }else{
//                [ZZPUtils showWarning:@"暂无联系方式"];
//            }
//        }else if(index == 103){
//            //            更多
//            
//            NSString *dealStatus = @"未成交";
//            if([GetHandleString(_dataDictionary, @"dealStatus") integerValue] == 0){
//                dealStatus = @"已成交";
//            }
//            
//            JMPopupMenuView *menuView = [JMPopupMenuView new];
//            menuView.targetView = manageBottomview.moreButtton;
//    
//            menuView.shouldShowSeparator = NO;
//            menuView.contentEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 15);
//            menuView.items = @[
//                [JMMenuItem itemWithImage:nil title:@"删除" handler:^(JMMenuItem * _Nonnull item) {
//                    NSLog(@"%@",item.title);
//                    [self shanChuYongHu];
//                }],
//                [JMMenuItem itemWithImage:nil title:@"共享" handler:^(JMMenuItem * _Nonnull item) {
//                    NSLog(@"%@",item.title);
//                    [self keHuQuGongXiang];
//                }],
//                [JMMenuItem itemWithImage:nil title:dealStatus handler:^(JMMenuItem * _Nonnull item) {
//                    NSLog(@"%@",item.title);
//                    [self performAfter:0.3 block:^{
//                        AlertRemindView *view = [AlertRemindView view];
//                        [ZZPUtils showAlertViewWithView:view andController:self];
//                        if([dealStatus isEqualToString:@"已成交"]){
//                            view.contentLabel.text = @"您确定要将客户更改为已成交吗？";
//                        }else{
//                            view.contentLabel.text = @"您确定要将客户更改为未成交吗？";
//                        }
//                        view.manageClickBlock = ^(NSInteger index) {
//                            [self dismissViewControllerAnimated:YES completion:nil];
//                            
//                            if(index == 102){
////                                成交
//                                [self chengJiaoKeHu];
//                            }
//                            
//                        };
//                    }];
//                }],
//                [JMMenuItem itemWithImage:nil title:@"放入公海" handler:^(JMMenuItem * _Nonnull item) {
//                    NSLog(@"%@",item.title);
//                    [self fangRuGongHaiManage];
//                }]
//            ];
//        
//        [menuView showWithAnimated:YES];
//            
//        }
//    };
//    [self shadowViewStyleWithView:manageBottomview];
//    manageBottomview.hidden = YES;
    
    
    
    gongHaiManageView = [GongHaiKeHuXiangQingDiBuView view];
    [self.view addSubview:gongHaiManageView];
    gongHaiManageView.sd_layout
    .leftEqualToView(self.view)
    .bottomEqualToView(self.view)
    .rightEqualToView(self.view)
    .heightIs(97);
    
    gongHaiManageView.manageClickBlock = ^(NSInteger index) {
        if(index == 100){
            //            分配
            [self gongHaiQuFenPei];
        }else if(index == 101){
            //            领取
            [self piLiangLingQuWithUserId:@[_customerId]];
        }else if(index == 102){
            //            删除
            [self shanChuYongHu];
        
        }
//        else if(index == 103){
//            //            转移公海
//            [self fangRuGongHaiManage];
//        }
        else if(index == 103){
            //            标记有效
//            [self fangRuGongHaiManage];
            AlertRemindView *view = [AlertRemindView view];
            [ZZPUtils showAlertViewWithView:view andController:self];
      
            view.contentLabel.text = @"确定要标记有效该客户吗？";
            view.manageClickBlock = ^(NSInteger index) {
                [self dismissViewControllerAnimated:YES completion:nil];
                if(index == 102){
                    [self biaoJiKeHuYouXiao];
                }
            };
        }
    };
    
    
    
    [self shadowViewStyleWithView:gongHaiManageView];

    gongHaiManageView.hidden = NO;
    
//    //按钮权限receive领取 distribute分配 delete删除
//    [self huoQuGongHaiQuanXian];
}

//标记客户有效
- (void)biaoJiKeHuYouXiao{
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:@[_customerId] forKey:@"ids"];
    [paraDic setValue:@"0" forKey:@"isEffective"];
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/crmCustomer/updateEffectiveById" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if (!error) {
            [ZZPUtils showWarning:@"标记成功"];
            [self getCoustomerInfoByCoustomerId];
        }
    }];
}


//根据用户ID获取用户信息
- (void)getCoustomerInfoByCoustomerId{
    NSString *url = [NSString stringWithFormat:@"/crmCustomer/queryById/%@",_customerId];
    [[ZZPRequest getWebUtil] postNetworkRequestURLString:url andParas:nil andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            _dataDictionary = [info objectForKey:@"data"];
        
            if([GetHandleString(_dataDictionary, @"star") integerValue] == 0){
                [self.customNavBar wr_setRightButtonWithImage:LocalImagePath(@"客户详情关注")];
            }else{
                [self.customNavBar wr_setRightButtonWithImage:LocalImagePath(@"客户详情已关注")];
            }
            //按钮权限receive领取 distribute分配 delete删除
            [self huoQuGongHaiQuanXian];
            
            [self zaiRuView];
        }
    }];
}

//按钮权限receive领取 distribute分配 delete删除
- (void)huoQuGongHaiQuanXian{
    
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:_poolId forKey:@"poolId"];
    [[ZZPRequest getWebUtil] postNetworkRequestURLString:@"/crmCustomerPool/queryAuthByPoolId" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            NSDictionary *dataDic = [info objectForKey:@"data"];
            NSInteger num = 0;
            if([GetHandleString(dataDic, @"distribute") integerValue] == 1){
                gongHaiManageView.fenPeiView.hidden = NO;
                num++;
            }else{
                gongHaiManageView.fenPeiView.hidden = YES;
            }
            
            if([GetHandleString(dataDic, @"receive") integerValue] == 1){
                gongHaiManageView.lingQUView.hidden = NO;
                num++;
            }else{
                gongHaiManageView.lingQUView.hidden = YES;
            }
            
            if([GetHandleString(dataDic, @"delete") integerValue] == 1){
                gongHaiManageView.shanChuView.hidden = NO;
                num++;
            }else{
                gongHaiManageView.shanChuView.hidden = YES;
            }
            
//            if([GetHandleString(dataDic, @"excelexport") integerValue] == 1){
//                gongHaiManageView.zhuanYiView.hidden = NO;
//                num++;
//            }else{
//                gongHaiManageView.zhuanYiView.hidden = YES;
//            }
            if([GetHandleString(dataDic, @"markEffective") integerValue] == 1){
                if ([GetHandleString(_dataDictionary, @"isEffective") boolValue]) {
                    gongHaiManageView.zhuanYiView.hidden = NO;
                    num++;
                }else{
                    gongHaiManageView.zhuanYiView.hidden = YES;
                }
            }else{
                gongHaiManageView.zhuanYiView.hidden = YES;
            }
            
            if(num > 0){
                gongHaiManageView.hidden = NO;
                isMeiQuanXian = NO;
                if(gongHaiManageView.fenPeiView.hidden == NO){
                    gongHaiManageView.fenPeiViewWidth.constant = (ScreenWidth-20)/num;
                }else{
                    gongHaiManageView.fenPeiViewWidth.constant = 0;
                }
                
                if(gongHaiManageView.lingQUView.hidden == NO){
                    gongHaiManageView.lingQuViewWidth.constant = (ScreenWidth-20)/num;
                }else{
                    gongHaiManageView.lingQuViewWidth.constant = 0;
                }
                
                if(gongHaiManageView.shanChuView.hidden == NO){
                    gongHaiManageView.shanChuViewWidth.constant = (ScreenWidth-20)/num;
                }else{
                    gongHaiManageView.shanChuViewWidth.constant = 0;
                }
            }else{
                gongHaiManageView.hidden = YES;
                isMeiQuanXian = YES;
                [self zaiRuView];
            }
            
        }
    }];
}



//批量领取
- (void)piLiangLingQuWithUserId:(NSArray *)userList{
    AlertRemindView *view = [AlertRemindView view];
    [ZZPUtils showAlertViewWithView:view andController:self];
    view.manageClickBlock = ^(NSInteger index) {
        [self dismissViewControllerAnimated:YES completion:^{
            if(index == 102){
    //            确定
                NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
                [paraDic setValue:userList forKey:@"ids"];
                [paraDic setValue:_poolId forKey:@"poolId"];
                [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/crmCustomer/receiveByIds" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
                    if(!error){
                        
                        if(_manageClickResultBlock){
                            _manageClickResultBlock(0);
                        }
                        [self shiFouLingQuChengGong:YES];
                        
                        [self.navigationController popViewControllerAnimated:YES];
                        
                    }else{
                        [self shiFouLingQuChengGong:NO];
                    }
                }];
            }
        }];
    };
}

//删除客户
- (void)shanChuYongHu{
    AlertRemindView *view = [AlertRemindView view];
    [ZZPUtils showAlertViewWithView:view andController:self];

    view.contentLabel.text = @"您确定要删除该公海客户吗？";

    view.manageClickBlock = ^(NSInteger index) {
        [self dismissViewControllerAnimated:YES completion:nil];
        if(index == 102){
            NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
            [paraDic setValue:_poolId forKey:@"poolId"];
            [paraDic setValue:@[_customerId] forKey:@"ids"];
            [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/crmCustomerPool/deleteByIds" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
                if(!error){
                    [self performAfter:0.5 block:^{
                        [ZZPUtils showWarning:@"删除成功"];
                    }];
                    
                    if(_manageClickResultBlock){
                        _manageClickResultBlock(0);
                    }
                    
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }];
        }
    };
}

//公海分配
- (void)gongHaiQuFenPei{
    GongHaiFenPeiViewController *gongHai = [[GongHaiFenPeiViewController alloc] init];
    gongHai.poolId = _poolId;
    gongHai.customerId = _customerId;
    [self.navigationController pushViewController:gongHai animated:YES];
}
//客户共享
- (void)keHuQuGongXiang{
    GongHaiFenPeiViewController *gongHai = [[GongHaiFenPeiViewController alloc] init];
    gongHai.currentType = 2;
    gongHai.customerId = _customerId;
    [self.navigationController pushViewController:gongHai animated:YES];
}

//转移公海
- (void)zhuanYiGongHai{
    GongHaiFenPeiViewController *gongHai = [[GongHaiFenPeiViewController alloc] init];
    gongHai.currentType = 3;
    gongHai.customerId = _customerId;
    [self.navigationController pushViewController:gongHai animated:YES];
}
//放入公海
- (void)fangRuGongHaiManage{
    GongHaiFenPeiViewController *gongHai = [[GongHaiFenPeiViewController alloc] init];
    gongHai.currentType = 1;
    gongHai.customerId = GetHandleString(_dataDictionary, @"customerId");
    [self.navigationController pushViewController:gongHai animated:YES];
}
//成交客户
- (void)chengJiaoKeHu{
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:[NSString stringWithFormat:@"%d",![GetHandleString(_dataDictionary, @"dealStatus") boolValue]] forKey:@"dealStatus"];
    [paraDic setValue:GetHandleString(_dataDictionary, @"customerId") forKey:@"ids"];
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/crmCustomer/setDealStatus" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            [self performAfter:0.5 block:^{
                if(![GetHandleString(_dataDictionary, @"dealStatus") boolValue]){
                    [ZZPUtils showWarning:@"已成交"];
                }else{
                    [ZZPUtils showWarning:@"已取消成交"];
                }
                NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:_dataDictionary];
                [dataDic setValue:[NSString stringWithFormat:@"%d",![GetHandleString(_dataDictionary, @"dealStatus") boolValue]] forKey:@"dealStatus"];
                _dataDictionary = dataDic;
                
            }];
        }
    }];
    
}

//是否领取成功
- (void)shiFouLingQuChengGong:(BOOL)isSuccess{
    AlertRemindView *view = [AlertRemindView view];
    [ZZPUtils showAlertViewWithView:view andController:self];
    view.leftButton.hidden = YES;
    view.rightButton.hidden = YES;
    view.centerButton.hidden = NO;
    if(isSuccess){
        view.topImage.image = LocalImagePath(@"公海领取弹窗成功");
        view.titleLabel.text = @"领取成功";
        view.contentLabel.text = @"恭喜领取成功！";
    }else{
        view.topImage.image = LocalImagePath(@"公海领取弹窗失败");
        view.titleLabel.text = @"领取失败";
        view.contentLabel.text = @"超过库容，领取失败";
    }
    view.manageClickBlock = ^(NSInteger index) {
        [self dismissViewControllerAnimated:YES completion:nil];
    };
}
- (void)shadowViewStyleWithView:(UIView *)view{
    view.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.1600].CGColor;
    view.layer.shadowOffset = CGSizeMake(2,0);
    view.layer.shadowOpacity = 1;
    view.layer.shadowRadius = 10;
    
    CGFloat radius = 10; // 圆角值大小
    if (@available(iOS 11.0, *)){
        // 设置 左上 右上 圆角
        view.layer.cornerRadius = radius;
        view.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
    }else {
        // 设置 左上 右上 圆角
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0,0,ScreenWidth,97) byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(radius, radius)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = CGRectMake(0,0,ScreenWidth,97);
        maskLayer.path = path.CGPath;
        view.layer.mask = maskLayer;
    }
}

- (void)zaiRuView{
    //标题数组
    NSArray *data = @[@"跟进记录",@"详细信息",@"操作日志"];
    WMZPageParam *param = PageParam()
    .wTitleArrSet(data)
    .wMenuBgColorSet([UIColor whiteColor])
    .wMenuTitleColorSet(rgba(90, 98, 112, 1))
    .wMenuTitleSelectColorSet(rgba(24, 27, 37, 1))
    .wMenuAnimalTitleGradientSet(YES)
    .wMenuTitleWidthSet((ScreenWidth-0)/3)
    .wMenuHeightSet(64)
    .wMenuIndicatorColorSet(rgba(40, 120, 255, 1))
    .wMenuIndicatorWidthSet(48)
    .wMenuIndicatorHeightSet(3)
    .wMenuIndicatorRadioSet(1.5)
    .wMenuPositionSet(PageMenuPositionCenter)
    .wMenuTitleUIFontSet([UIFont systemFontOfSize:16])
    .wMenuTitleSelectUIFontSet([UIFont systemFontOfSize:16 weight:UIFontWeightMedium])
    //控制器数组
    .wViewControllerSet(^UIViewController *(NSInteger index) {
       
        if(index == 0){
            KeHuXiangQingGenJinJiLuViewController*vc = KeHuXiangQingGenJinJiLuViewController.new;
            vc.customerId = self.customerId;
            return vc;
        }
        
        if(index == 2){
            KeHuXiangQingCaoZuoRiZhiViewController*vc = KeHuXiangQingCaoZuoRiZhiViewController.new;
            vc.customerId = self.customerId;
            return vc;
        }
        
        KeHuXiangXinXiViewController*vc = KeHuXiangXinXiViewController.new;
        vc.customerId = self.customerId;
        vc.poolId = _poolId;
        vc.isGongHai = YES;
        return vc;
    })
    .wCustomTabbarYSet(^CGFloat(CGFloat nowY) {
        return nowY;
    })
    .wBouncesSet(YES)
    //控制器结束切换
    .wEventEndTransferControllerSet(^(UIViewController *oldVC, UIViewController *newVC, NSInteger oldIndex, NSInteger newIndex) {
       NSLog(@"结束切换 %ld %ld",oldIndex,newIndex);
        _currentIndex = newIndex;
        
//        if(newIndex == 0){
//            manageBottomview.hidden = YES;
//            gongHaiManageView.hidden = NO;
//        }else{
//            manageBottomview.hidden = NO;
//            gongHaiManageView.hidden = YES;
//        }
     })
    //悬浮开启
    .wTopSuspensionSet(NO)
    //顶部可下拉
    .wBouncesSet(NO)
    //头视图y坐标从导航栏开始
    .wFromNaviSet(NO)
    //导航栏透明度变化
    .wNaviAlphaSet(YES)
    .wMenuAnimalSet(PageTitleMenuAiQY)
    .wMenuDefaultIndexSet(_currentIndex)
    .wMenuHeadViewSet(^UIView *{
        GongHaiKeHuXiangQingDingBuView *topView = [GongHaiKeHuXiangQingDingBuView view];
        topView.frame = CGRectMake(0, 0, ScreenWidth, NavaBarHeight+116+14);
        
        topView.nameLabel.text = GetHandleString(_dataDictionary, @"customerName");
        topView.phoneLabel.text = GetHandleString(_dataDictionary, @"mobile");
        topView.genJinShiJianLabel.text = GetHandleString(_dataDictionary, @"lastTime");
        topView.zhuangTaiLabel.text = GetHandleString(_dataDictionary, @"level");
        
        return topView;
    });
    //头部
    param.wCustomDataViewHeight = ^CGFloat(CGFloat nowY) {
        /// 再减掉父类的菜单高度
        ///
        CGFloat height = nowY-NavaBarHeight-116-14-97;
        if(isMeiQuanXian){
            height = nowY-NavaBarHeight-116-14;
        }
        return height;
    };

    self.param = param;
}




- (void)setupNavBar{
    
    [self.view addSubview:self.customNavBar];
    [self.customNavBar wr_setBottomLineHidden:YES];
    if (self.navigationController.childViewControllers.count != 1) {
        [self.customNavBar wr_setLeftButtonWithImage:[UIImage imageNamed:@"返回"]];
    }
}



- (WRCustomNavigationBar *)customNavBar{
    if (_customNavBar == nil) {
        _customNavBar = [WRCustomNavigationBar CustomNavigationBar];
        _customNavBar.tintColor = [UIColor whiteColor];
        _customNavBar.titleLabelColor = rgba(24, 27, 37, 1);
        _customNavBar.barBackgroundImage = LocalImagePath(@"导航栏");
        _customNavBar.titleLabelFont = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
        _customNavBar.title = @"客户详情";
    }
    return _customNavBar;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end



